﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Interop = System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using Json = Newtonsoft.Json;

// note: アプリの設定をJsonで保存／ロードするフレームワークを提供

namespace SimonPG {

    [Interop.ComVisible(false)]
    public static class ConfigAsJsonStatic {

        public static T Load<T>(string path) where T : new() {
            // T型の設定格納クラスを生成

            try {
                var text = File.ReadAllText(path);
                var config = Json.JsonConvert.DeserializeObject<T>(text);
                return config;

            } catch (Exception) {
                return new T();
            }
        }

        public static void Save(string path, object config) {
            // T型の設定格納クラスを保存

            var text = Json.JsonConvert.SerializeObject(config, Json.Formatting.Indented);
            File.WriteAllText(path, text);
        }
    }

    [Interop.ComVisible(false)]
    public class ConfigAsJsonBase<T> where T : new() {
        // assume: このクラスを継承して固有の設定格納クラスを作成

        // sec: load/save

        public static T Load() {
            var path = Path.Combine(FilePath, FileName);
            return ConfigAsJsonStatic.Load<T>(path);
        }

        public void Save() {
            var path = Path.Combine(FilePath, FileName);
            ConfigAsJsonStatic.Save(path, this);
        }

        // sec: settings

        public static string FileName = "test.json";
        public static string FilePath = Application.UserAppDataPath;
    }

    // sec: how to use
    
    [Interop.ComVisible(false)]
    public class ExampleConfig : ConfigAsJsonBase<ExampleConfig> {
        // assume: 設定格納クラスの例

        // sec: 設定項目

        public bool Visible = true;
    }
}
